<template>
  <a-modal
    :visible="visible"
    width="1100px"
    title="选择成员"
    :destroyOnClose="true"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-row>
      <a-col :span="7" class="leftTree">
        <h2>组织架构</h2>
        <a-tree :load-data="onLoadData" :tree-data="treeData" @select="queryUsers" />
      </a-col>
      <a-col :span="17" class="rightData">
        <a-row class="partMargin">
          <a-col :span="12">
            <h2>{{currentSeletedNode.title}}（{{count}}人）</h2>
          </a-col>
        </a-row>

        <a-form layout="inline">
          <a-form-item label="姓名">
            <a-input v-model="searchForm.name" />
          </a-form-item>
          <a-form-item label="账号">
            <a-input v-model="searchForm.account" />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="handleSubmit">查询</a-button>
          </a-form-item>
        </a-form>

        <a-table
          :columns="columns"
          :data-source="tableData"
          class="tableMargin"
          :pagination="false"
          :row-selection="{ onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
          :loading="loading"
          rowKey="uiId"
        >
          <span slot="head" slot-scope="record">
            <a-avatar size="large" :src="record.headPortrait || defaultAvatar" />
          </span>
          <template slot="name" slot-scope="text, record">
            <span>
              {{record.name}}
              <img v-if="record.isLeader===1" :src="xing" />
            </span>
          </template>
        </a-table>
        <p style="margin: 18px 0; text-align: center;">
          <a-button type="primary" @click="selectSalesPerson">确认添加</a-button>
          共选中 {{chosenNum}} 个成员
        </p>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { queryDeptList, queryDeptUserList } from '@/api/systemPersonnelManage'
import { Tree } from 'ant-design-vue'
import xing from '@/../static/images/xing.png'
import defaultAvatar from '@/../static/images/defaultAvatar.png'

const defaultForm = function () {
  return { name: '', account: '' }
}

export default {
  name: 'sales-person-modal',
  props: {
    visible: Boolean,
    dataRole: {
      type: String,
      default: 'LAND_SELL'
    }
  },
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        customRender: (text, row, index) => {
          return index + 1
        }
      },
      {
        width: 60,
        scopedSlots: { customRender: 'head' }
      },
      {
        title: '姓名',
        ellipsis: true,
        scopedSlots: { customRender: 'name' }
      },
      {
        title: '职务',
        dataIndex: 'position',
        ellipsis: true
      },
      {
        title: '所属部门',
        dataIndex: 'deptName',
        ellipsis: true
      },
      {
        title: '账号',
        dataIndex: 'account',
        ellipsis: true
      }
    ]

    return {
      xing,
      defaultAvatar,
      treeData: [],
      currentSeletedNode: { key: 0, title: '', isDefault: 1 },
      count: 0,
      columns,
      tableData: [],
      searchForm: defaultForm(),
      loading: false,
      selectedRowKeys: [],
      chosenNum: 0
    }
  },
  components: {
    [Tree.name]: Tree
  },
  methods: {
    initData () {
      this.treeData = []
      this.chosenNum = 0
      this.tableData = []
    },
    getCheckboxProps (record) {
      return {
        props: {
          defaultChecked: record.isSelected === 1,
          disabled: record.isSelected === 1
        }
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      const newSelected = selectedRows.filter(record => !record.isSelected)
      const temp = newSelected.map(record => {
        return record.uiId
      })
      this.selectedRowKeys = temp
      this.chosenNum = temp.length
    },
    handleCancel () {
      this.$emit('set-visible', false)
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        queryDeptList({ parentId: treeNode.dataRef.key }).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value, index) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              isDefault: value.isDefault
            })
          })
          treeNode.dataRef.children = childrenData
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    queryUsers (selectedKeys, e) {
      this.loading = true
      queryDeptUserList({ deptId: e.node.dataRef.key, dataRole: this.dataRole }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data
        this.count = rsp.data.length
        this.currentSeletedNode = e.node.dataRef

        this.deptId = e.node.dataRef.key // 触发更新modal数据
      }).catch(() => { this.loading = false })
    },
    handleSubmit () {
      this.loading = true
      queryDeptUserList({ deptId: this.currentSeletedNode.key, name: this.searchForm.name, account: this.searchForm.account, dataRole: this.dataRole }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data
        this.count = rsp.data.length
      }).catch(() => { this.loading = false })
    },
    selectSalesPerson () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请先选择成员')
      } else {
        this.$emit('select-sales-person', this.selectedRowKeys.join(','))
      }
    }
  },
  watch: {
    visible () {
      if (this.visible) {
        this.searchForm = defaultForm()
        this.initData()
        queryDeptList({ parentId: 0 }).then(rsp => {
          let initData = []
          rsp.data.forEach((value, index) => {
            initData.push({
              title: value.name,
              key: value.deptId,
              isDefault: value.isDefault
            })
          })
          this.treeData = initData
          return initData[0]
        }).then(data => {
          this.loading = true
          // 默认加载所有
          queryDeptUserList({ deptId: data.key, dataRole: this.dataRole }).then(rsp => {
            this.loading = false
            this.tableData = rsp.data
            this.count = rsp.data.length
            this.currentSeletedNode = data
            this.deptId = data.key // 触发更新modal数据
          }).catch(() => { this.loading = false })
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.leftTree {
  overflow-x: auto;
  min-height: 500px;
}

.rightData {
  padding-left: 20px;
  border-left: 1px solid #f0f2f5;

  a.linkStyle {
    margin-right: 5px;
  }
}
</style>
